<?php
declare (strict_types=1);

namespace app\index\controller;

use think\exception\ValidateException;
use think\facade\View;
use think\response\Json;
use app\common\model\Order as OrderModel;

class Order extends Base
{
    public function index()
    {
        $temporary = OrderModel::getTemporary($this->user);
        if (empty($temporary) || empty($temporary['products'])) {
            return redirect('/');
        }
        View::assign('temporary', $temporary);

        return View::fetch();
    }

    public function submit()
    {
        $param = $this->request->post();

        return json(OrderModel::submit($param, $this->user));
    }

    public function payment()
    {
        $id = $this->request->param('id');
        $info = OrderModel::where(['id' => $id, 'uid' => $this->user->id, 'status' => 1, 'pay_state' => 1])->find();
        if (!$info) {
            return redirect('/');
        }
        View::assign('info', $info);

        return View::fetch();
    }

    public function confirmPayment(): Json
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'confirmPayment');
        } catch (ValidateException $e) {
            return json(['code' => -1, 'msg' => $e->getError()]);
        }
        if (!in_array($param['pay_way'], ['alipay', 'wechat']) && md5($param['pay_password']) != $this->user->pay_password) {
            return json(['code' => -1, 'msg' => '支付密码错误']);
        }

        return json(OrderModel::confirmPayment($param, $this->user));
    }

    public function my_order()
    {
        return View::fetch();
    }

    public function my_order_details()
    {
        $id = $this->request->param('id');
        $info = OrderModel::where(['id' => $id])->find();
        if (empty($info)) {
            return redirect('/');
        }
        View::assign('info', $info);

        return View::fetch();
    }

    public function getList(): Json
    {
        $param = $this->request->param();
        $map = ['uid' => $this->user->id, 'is_del' => 0];
        if (!empty($param['type'])) {
            $map['status'] = $param['type'];
        }

        return json(OrderModel::getPageList($map, '*', $param['page'], 20, false, ['products']));
    }

    public function edit(): Json
    {
        $param = $this->request->post();

        return json(OrderModel::edit($param));
    }
}